package com.clothing.dao.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.clothing.dao.LeaveMessageDao;
import com.clothing.entity.LeaveMessage;
import com.clothing.utils.Utils;
import com.clothing.utils.page.Page;
import com.clothing.utils.page.Pageable;

/**
 * @ClassName: LeaveMessageDaoImpl 
 * @Description: TODO(Dao) 
 * @author Charles.Tao 
 * @date 2017年9月6日 下午3:40:20 
 * @version 1.0
 */
@Repository
public class LeaveMessageDaoImpl extends BaseDaoImpl<LeaveMessage, Long> implements LeaveMessageDao
{
    @Override
    public Page<LeaveMessage> findPageByUser(Long userId, Pageable pageable)
    {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<LeaveMessage> criteriaQuery = criteriaBuilder
            .createQuery(LeaveMessage.class);
        Root<LeaveMessage> root = criteriaQuery.from(LeaveMessage.class);
        criteriaQuery.select(root);
        Predicate predicate = criteriaBuilder.or(criteriaBuilder
            .equal(root.get("bigUser").get("id"), userId), criteriaBuilder
            .equal(root.get("smallUser").get("id"), userId));
        criteriaQuery.where(predicate);
        
        return findPage(criteriaQuery, pageable);
    }
    
    @Override
    public LeaveMessage findOne(Long userOne, Long userTwo)
    {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<LeaveMessage> criteriaQuery = criteriaBuilder
            .createQuery(LeaveMessage.class);
        Root<LeaveMessage> root = criteriaQuery.from(LeaveMessage.class);
        criteriaQuery.select(root);
        Long smallUserId = 0L;
        Long bigUserId = 0L;

        if (userOne < userTwo)
        {
            smallUserId = userOne;
            bigUserId = userTwo;
        }
        else
        {
            smallUserId = userTwo;
            bigUserId = userOne;
        }
        
        Predicate predicate = criteriaBuilder.and(criteriaBuilder
            .equal(root.get("bigUser").get("id"), bigUserId), criteriaBuilder
            .equal(root.get("smallUser").get("id"), smallUserId));
        criteriaQuery.where(predicate);
        List<LeaveMessage> friends = findList(criteriaQuery, null, 1, null, null);

        if (Utils.isEmpty(friends))
        {
            return null;
        }

        return friends.get(0);
    }
}
